import { reqCartList,reqDeleteCartListById,reqChangeCheckedById } from "@/api"
const state = {
    cartInfoList: []
}
const actions = {
    async cartList({commit}) {
        let result = await reqCartList()
        if (result.data.code === 200) {
            commit("CARTLIST",result.data.data)
        }
    },
    async deleteCartListById({ commit },skuId) {
        let result = await reqDeleteCartListById(skuId)
        if (result.data.code === 200) return "ok"
        else return Promise.reject(new Error("fail"))
    },
    async changeCheckedById({ commit }, { skuId, isChecked }) {
        let result = await reqChangeCheckedById(skuId, isChecked)
        if (result.data.code === 200) return "ok"
        else return Promise.reject(new Error("fail"))
    },
    deleteAllCheckedCart({ dispatch, getters }) {
        let promiseArray=[]
            getters.cartInfoList.forEach(item => {
                // if (item.isChecked == 1) {
                //     let promise = dispatch("deleteCartListById", item.skuId)   
                //     promiseArray.push(promise)
                // }       
                let promise = item.isChecked == 1 ? dispatch("deleteCartListById", item.skuId) : '';
                promiseArray.push(promise)                
            })
        return Promise.all(promiseArray)
    },
    updateAllCheckedOfCart({dispatch,state},isChecked) {
        let checked = isChecked ? "1" : "0"
        let promiseArray=[]
        state.cartInfoList.forEach(item => {
            let promise = dispatch("changeCheckedById", { skuId: item.skuId, isChecked: checked })
            promiseArray.push(promise)
        })
        return Promise.all(promiseArray);
    }
}
const mutations = {
    CARTLIST(state, data) {
        state.cartInfoList=data[0]===undefined?[]:data[0].cartInfoList
    }
}
const getters = {
    cartInfoList(state) {
        return state.cartInfoList || []
    }
}
export default {
    state,
    actions,
    mutations,
    getters
}